'use client'

import * as React from 'react'
import { cn } from '@/lib/utils'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Button } from '@/components/ui/button'

import { useSelector, useDispatch } from 'react-redux'
import { setProjects, setCurProject, selectProjects, selectCurProject } from '@/store/project-slice'
import useRequest from '@/utils/request'

import RouterHook from '@/components/RouterHook'

export default function ProjectSwitcher({ isCollapsed }) {
  const [hasMounted, setHasMounted] = React.useState(false)

  const projects = useSelector(selectProjects)
  const curProject = useSelector(selectCurProject)
  const dispatch = useDispatch()
  const request = useRequest()

  React.useEffect(() => {
    const fetchProjects = async () => {
      try {
        const response = await request.get('red_growth/project?type=all')
        return response.data
      } catch (error) {
        console.error('Error fetching data:', error)
        return []
      }
    }

    fetchProjects().then(data => {
      dispatch(setProjects(data))

      if (!curProject && data.length > 0) {
        dispatch(setCurProject(data[0]))
      }

      setHasMounted(true)
    })
  }, [])

  const handleValueChange = e => {
    const curProject = projects.find(project => project.id === e)
    dispatch(setCurProject(curProject))
  }

  if (!hasMounted) {
    return null
  }

  if (projects.length <= 0) {
    return (
      <RouterHook path="/projects/add">
        <Button className="mt-4" variant="outline">
          Add Project
        </Button>
      </RouterHook>
    )
  }

  if (!curProject) {
    return null
  }

  return (
    <Select defaultValue={curProject.id} value={curProject.id} onValueChange={e => handleValueChange(e)}>
      <SelectTrigger
        className={cn(
          'flex items-center gap-2 [&>span]:line-clamp-1 [&>span]:flex [&>span]:w-full [&>span]:items-center [&>span]:gap-1 [&>span]:truncate [&_svg]:h-4 [&_svg]:w-4 [&_svg]:shrink-0',
          isCollapsed && 'flex h-9 w-9 shrink-0 items-center justify-center p-0 [&>span]:w-auto [&>svg]:hidden'
        )}
        aria-label="Select project"
      >
        <SelectValue placeholder="Select an project">
          {projects.find(project => project.id === curProject.id)?.icon}
          <span className={cn('ml-2', isCollapsed && 'hidden')}>
            {projects.find(project => project.id === curProject.id)?.brand}
          </span>
        </SelectValue>
      </SelectTrigger>
      <SelectContent>
        {projects.map(project => (
          <SelectItem key={project.id} value={project.id}>
            <div className="flex items-center gap-3 [&_svg]:h-4 [&_svg]:w-4 [&_svg]:shrink-0 [&_svg]:text-foreground">
              {/* {project.icon} */}
              {project.brand}
            </div>
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  )
}
